#!/usr/bin/env python
"""
@author: Sergiy Tsymbalyuk
"""

import MySQLdb, sys
from getpass import getpass

dbs = {
    'finder': ['departments',
               'departs_sections',
               'descriptions',
               'doc_types',
               'docs_sections',
               'docs_tags',
               'documents',
               'favorites',
               'files',
               'sections',
               'tags',
               'users'],
    
    'kadry': ['awards',
              'awards_change',
              'children',
              'department',
              'kvalification',
              'osvita',
              'osvita_change',
              'personal',
              'post',
              'post_change',
              'post_type',
              'rang_change',
              'staff',
              'udk',
              'users',
              'vacation',
              'vidpustka',
              'who_awards',
              'workbook'],
    
    'zvity': ['komun_elek',
              'komun_gaz',
              'komun_teplo',
              'komun_voda',
              'otdels',
              'tel'],
    'site': ['weather_forecast',
             'news_content',
             'news_rss'],
}

def transfer_tables():
    # user = raw_input('User: ')
    user = sys.argv[1]
    # passwd = getpass()
    passwd = sys.argv[2]
    
    conn = MySQLdb.connect(host='localhost', user=user, passwd=passwd, db='chowa')
    cur = conn.cursor()
    
    for db in dbs:
        for table in dbs[db]:
            params = {'db': db, 'table': table}
            src = '%(db)s.%(table)s' % params
            dst = 'm_%(db)s_%(table)s' % params
            
            cur.execute('DROP TABLE IF EXISTS %s' % dst)
            cur.execute('CREATE TABLE IF NOT EXISTS %s LIKE %s' % (dst, src))
            cur.execute('ALTER TABLE %s ENGINE = MyISAM' % dst)
            try:
                cur.execute('DELETE FROM %s WHERE id=0' % src)
            except:
                pass
            cur.execute('INSERT %s SELECT * FROM %s' % (dst, src))
            print 'Table %s.%s transferred.' % (db, table)
    
    cur.close()
    conn.close()

if __name__ == '__main__':
    transfer_tables()

